// Copyright (c) 2025 Shenzhen Kaihong Digital Industry Development Co., Ltd.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

use log::{error, trace};
use maestro_derive::MsgTag;
use ohmw_derive::{Decode, Encode};

use crate::system::SystemHandles;

#[derive(Encode, Decode, MsgTag)]
#[msg_tag(case = "snake_case")]
pub struct QueryTopicMsgTypeRet {
    pub success: String,
    pub topic_name: String,
    pub msg_type: String,
}

pub fn query_topic_msg_type(topic_name: &str) -> QueryTopicMsgTypeRet {
    if !SystemHandles::ensure_ros_initialized() {
        return QueryTopicMsgTypeRet {
            topic_name: topic_name.to_string(),
            success: "ros not inited".to_string(),
            msg_type: "".to_string(),
        };
    }

    match SystemHandles::query_topic_msg_type(topic_name) {
        Some(msg_type) => {
            trace!("query_topic_msg_type: topic_name: {}, msg_type: {}", topic_name, msg_type);
            QueryTopicMsgTypeRet {
                topic_name: topic_name.to_string(),
                success: "ok".to_string(),
                msg_type: msg_type.clone(),
            }
        },
        None => {
            error!("query_topic_msg_type: msg type for {} not found", topic_name);
            QueryTopicMsgTypeRet {
                topic_name: topic_name.to_string(),
                success: "topic not found".to_string(),
                msg_type: "".to_string(),
            }
        },
    }
}
